import React, { useState } from "react";
import "./less/login.less";
import logoImg from "../assets/logo.png";
import { Form, Input, Button, Spin, message } from "antd";
import { useNavigate } from "react-router-dom";
import { registerAccount } from "../network/api";

export default function Register() {
  // 加载动画
  let [isLoading, setLoading] = useState(false);
  //路由跳转
  const navigate = useNavigate();

  const onFinish = async ({ username, password }) => {
    isLoading = setLoading(true);

    try {
      await registerAccount({ username, password });

      message.success("注册成功!");
      setTimeout(() => {
        navigate("/login");
      }, 800);
    } catch (error) {
    } finally {
      isLoading = setLoading(false);
    }
  };

  const onFinishFailed = (errorInfo) => {};

  return (
    <div className="login-wrapper">
      <Spin tip="Loading..." spinning={isLoading}>
        <div className="login-box">
          <img src={logoImg} alt="" />
          <Form
            name="basic"
            initialValues={{
              remember: true,
            }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              name="username"
              rules={[
                {
                  required: true,
                  message: "请输入用户名!",
                },
              ]}
            >
              <Input placeholder="请输入用户名" size="large" />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  message: "请输入密码!",
                },
              ]}
            >
              <Input.Password placeholder="请输入密码" size="large" />
            </Form.Item>
            <Form.Item
              name="confirm"
              dependencies={["password"]}
              hasFeedback
              rules={[
                {
                  required: true,
                  message: "请确认密码!",
                },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue("password") === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error("两次密码不一致!"));
                  },
                }),
              ]}
            >
              <Input.Password placeholder="请再次输入密码" size="large" />
            </Form.Item>
            <Form.Item>
              <Button type="primary" block size="large" htmlType="submit">
                注册
              </Button>
            </Form.Item>
          </Form>
        </div>
      </Spin>
    </div>
  );
}
